import { onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { getTimeState } from '@/utils'
import { login_sign_in_get } from '@/api/modules/login.js'
import { initDynamicRouter } from '@/routers/modules/dynamicRouter'

import { HOME_URL } from '@/config'

export const useDingtalkLogin = router => {
  let isLoggedIn = false
  const loginSignIn = async (params, callback) => {
    const userStore = useUserStore()
    // 登录
    const result = await login_sign_in_get(params).catch(() => {
      callback && callback()
      isLoggedIn = true
    })
    isLoggedIn = true
    if (result.code === 200 && result.data) {
      await userStore.setToken(result.data.satoken)
      await userStore.setLoginId(result.data.loginId)
      await userStore.setUserInfo(result.data)
      // 2.添加动态路由
      await initDynamicRouter()
      ElNotification({
        title: getTimeState(),
        message: '欢迎登录集美业务中台',
        type: 'success',
        duration: 3000
      })

      router.push(HOME_URL)
    }
  }
  /**
   * 钉钉api登录
   */
  const dingTalkLoginQR = function () {
    // appid
    const appid = import.meta.env.VITE_APPID
    // 登录重定向url
    const redirect_uri = import.meta.env.DEV
      ? 'http://localhost:8080'
      : import.meta.env.VITE_redirect

    const ddLogin = window.DTFrameLogin
    ddLogin(
      {
        id: 'self_defined_element',
        width: 300,
        height: 300
      },
      {
        redirect_uri: encodeURIComponent(redirect_uri),
        client_id: appid,
        scope: 'openid',
        response_type: 'code',
        state: 'dddd',
        prompt: 'consent'
      },
      function ({ authCode }) {
        !isLoggedIn &&
          loginSignIn(
            {
              authCode
            },
            () => {
              ElMessage.error(`登录失败`)
              ddLogin.reloadQRCode()
            }
          )
      },
      errorMsg => {
        // 这里一般需要展示登录失败的具体原因,可以使用toast等轻提示
        console.error(`errorMsg of errorCbk: ${errorMsg}`)
        ddLogin.reloadQRCode()
      }
    )
  }
  onMounted(() => {
    dingTalkLoginQR()
  })
}
